package com.zf.shuashua.ui.mine;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.ViewModelProviders;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.SlidingTabLayout;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.meis.base.mei.annotation.PullToRefresh;
import com.meis.base.mei.utils.NumberUtils;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.R;
import com.zf.shuashua.api.AbsCallback;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.base.BaseActivity1;
import com.zf.shuashua.bean.AddBlack;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.FocusType;
import com.zf.shuashua.bean.Me;
import com.zf.shuashua.event.HotVideoEvent;
import com.zf.shuashua.ui.home.BlackPopup;
import com.zf.shuashua.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

@PullToRefresh  // 一行代码 注入下拉刷新功能
public class FriendsDetailsActivity extends BaseActivity1 implements View.OnClickListener {
    FriedsDetailsVM VM;
    private Toolbar mToolbar;
    private TextView mTvTitle;
    private String[] titles = {"作品", "喜欢"};
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private ViewPager vp;
    private MyPagerAdapter adapter;
    private SlidingTabLayout tabLayout;
    private ImageView imgAvatar;
    private TextView tvName;
    private TextView tvFocus;
    private TextView tvFans;
    private TextView tvZan;
    private TextView tvSign;
    private TextView tvIsFocus;
    private TextView mTvRight;
    private String user_id;
    private LinearLayout llFocus;
    private LinearLayout llFans;
    private Me data;

    private int currentTab = 0;

    @Override
    public void onRefreshing() {
        super.onRefreshing();
        VM.getDataRefresh(user_id);
    }


    @Override
    protected void initView() {
        setToolbarLayout(R.layout.inc_toolbar);
        VM = ViewModelProviders.of(this).get(FriedsDetailsVM.class);
        user_id = getIntent().getStringExtra("USER_ID");
        mToolbar = findViewById(R.id.toolbar);
        mTvTitle = findViewById(R.id.tv_title);
        mTvRight = findViewById(R.id.tv_right);
        initToolBar(mToolbar, true, "");
        mTvRight.setBackground(getResources().getDrawable(R.mipmap.ic_more));
        imgAvatar = findViewById(R.id.imgAvatar);
        tvName = findViewById(R.id.tvName);
        tvFocus = findViewById(R.id.tvFocus);
        tvFans = findViewById(R.id.tvFans);
        tvZan = findViewById(R.id.tvZan);
        tvSign = findViewById(R.id.tvSign);
        tvIsFocus = findViewById(R.id.tvIsFocus);
        vp = findViewById(R.id.vp);
        tabLayout = findViewById(R.id.tl);
        llFocus = findViewById(R.id.llFocus);
        llFans = findViewById(R.id.llFans);
        llFocus.setOnClickListener(this);
        llFans.setOnClickListener(this);
        tvIsFocus.setOnClickListener(this);
        mTvRight.setOnClickListener(this);
        adapter = new MyPagerAdapter(getSupportFragmentManager());
        fragments.add(MineListVideoFragment.newInstance(user_id));
        fragments.add(MineLikeVideoFragment.newInstance(user_id));
        vp.setAdapter(adapter);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentTab = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabLayout.setViewPager(vp, titles);
        VM.getRefresh().observe(this, me -> {
            setUI(me);
            setRefreshing(false);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (VM != null) {
            VM.getDataRefresh(user_id);
        }
    }

    public void setUI(Me data) {
        if (data == null) {
            return;
        }
        this.data = data;
        Store.getInstance().setAgent_code(data.getData().getAgent_code() + "");
        Store.getInstance().setUserName(data.getData().getName());
        if (Store.getInstance().getuserId().equals(data.getData().getId() + "")) {
            tvIsFocus.setVisibility(View.GONE);
        } else {
            if (data.getData().getFollow_status() == 0) {
                tvIsFocus.setText("关注");
                tvIsFocus.setSelected(true);
            } else {
                tvIsFocus.setText(data.getData().getFollow_status_text());
                tvIsFocus.setSelected(false);
            }

            EventBus.getDefault().post(new HotVideoEvent(data.getData().getFollow_status() == 1));
        }
        tvName.setText(data.getData().getName());
        tvFocus.setText(NumberUtils.INSTANCE.convertOneDecimalW(data.getData().getFollow_count()));
        tvFans.setText(NumberUtils.INSTANCE.convertOneDecimalW(data.getData().getFans_count()));
        tvZan.setText(NumberUtils.INSTANCE.convertOneDecimalW(data.getData().getPraise_count()));
        if (!TextUtils.isEmpty(data.getData().getSignature())) {
            tvSign.setText(data.getData().getSignature());
        }
        Glide.with(this).load(data.getData().getAvatar())
                .error(R.mipmap.ic_avatar_default)
                .placeholder(R.mipmap.ic_avatar_default)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))//圆形
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imgAvatar);

    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_friends_details;
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }
    }

    float dx;
    float dy;

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                dx = event.getX();
                dy = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                float disX = event.getX() - dx;
                float disY = dy - event.getY();
                if (currentTab == 0 && disX > 60 && disX > Math.abs(disY) + 20) {
                    Intent intent = getIntent();
                    setResult(Activity.RESULT_OK, intent);
                    this.finish();
                    overridePendingTransition(R.anim.left_in, R.anim.right_out);
                }
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    @Override
    public void onClick(View view) {
        if (!Store.getInstance().isLogin()) {
            startActivity(new Intent(this, LoginActivity.class));
        } else {
            switch (view.getId()) {
                case R.id.llFocus:
                    startActivityForResult(new Intent(this, FocusListActivity.class).putExtra("FocusList", 0).putExtra("FocusList1", 1).putExtra("USER_ID", user_id), MineFragment.FOCUSLISTACTIVITY);
                    break;
                case R.id.llFans:
                    startActivityForResult(new Intent(this, FocusListActivity.class).putExtra("FocusList", 1).putExtra("FocusList1", 0).putExtra("USER_ID", user_id), MineFragment.FOCUSLISTACTIVITY);
                    break;
                case R.id.tvIsFocus:
                    if (data != null && data.getData() != null) {
                        HttpData.getInstance().getFocusType(data.getData().getId(), new AbsCallback<BaseData<FocusType>>() {
                            @Override
                            public void onRealSuccess(BaseData<FocusType> data) {
                                VM.getDataRefresh(user_id);
                            }

                            @Override
                            public void onFail(int errCode, String errMsg) {
                                LogUtil.d(errMsg);
                            }
                        });
                    }
                    break;
                case R.id.tv_right:
                    new XPopup.Builder(this)
                            .asBottomList("", new String[]{"举报", "拉黑", "取消"},
                                    null, -1,
                                    (position, text) -> {
                                        if (position == 0) {
                                            //举报
                                            new XPopup.Builder(FriendsDetailsActivity.this)
                                                    .asBottomList("请选择举报类型", new String[]{"广告欺诈", "淫秽色情", "骚扰谩骂", "反动政治", "取消"},
                                                            null, -1,
                                                            new OnSelectListener() {
                                                                @Override
                                                                public void onSelect(int position, String text) {
                                                                    if (position == 4)
                                                                        return;//用户取消时return

                                                                    HttpData.getInstance().addReport(Integer.toString(position + 1), "user", user_id, new ACallback<AddBlack>() {
                                                                        @Override
                                                                        public void onSuccess(AddBlack data) {
                                                                            if (data.getCode() == 200) {
                                                                                ToastUtil.show(FriendsDetailsActivity.this, "举报成功");
                                                                            }
                                                                        }

                                                                        @Override
                                                                        public void onFail(int errCode, String errMsg) {

                                                                        }
                                                                    });

                                                                }
                                                            })
                                                    .show();
                                        } else if (position == 1) {
                                            //拉黑
                                            new XPopup.Builder(FriendsDetailsActivity.this)
                                                    .asCustom(new BlackPopup(FriendsDetailsActivity.this, user_id))
                                                    .show();

                                        } else {

                                        }
                                    })
                            .show();
                    break;

            }
        }
    }
}


